<?php

class WorthlessSharesController extends AppController {

    var $name = 'WorthlessShares';
    var $paginate = array('limit' => 60, 'order' => array('WorthlessShare.LineNo' => 'DESC'));

    /* backup the db OR just a table */

    function admin_backup_tables($host, $user, $pass, $name, $tables = '*') {
        $return = '';
        //$link = mysql_connect($host, $user, $pass);
      //  mysql_select_db($name, $link);

        //get all of the tables
        if ($tables == '*') {
            $tables = array();
            $result = mysql_query('SHOW TABLES');
            while ($row = mysql_fetch_row($result)) {
                $tables[] = $row[0];
            }
        } else {
            $tables = is_array($tables) ? $tables : explode(',', $tables);
        }
        //pr($tables);exit;
        //cycle through
        foreach ($tables as $table) {
            $result = mysql_query('SELECT * FROM ' . $table);
            $num_fields = mysql_num_fields($result);

            $return.= 'DROP TABLE ' . $table . ';';
            $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
            $return.= "\n\n" . $row2[1] . ";\n\n";

            for ($i = 0; $i < $num_fields; $i++) {
                while ($row = mysql_fetch_row($result)) {
                    $return.= 'INSERT INTO ' . $table . ' VALUES(';
                    for ($j = 0; $j < $num_fields; $j++) {
                        $row[$j] = addslashes($row[$j]);
                        $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
                        if (isset($row[$j])) {
                            $return.= '"' . $row[$j] . '"';
                        } else {
                            $return.= '""';
                        }
                        if ($j < ($num_fields - 1)) {
                            $return.= ',';
                        }
                    }
                    $return.= ");\n";
                }
            }
            $return.="\n\n\n";
        }

        //save file
        $file_name='db-backup-' . date('y-m-d_H:i:s') . '-' . (md5(implode(',', $tables))) . '.sql';
        $handle = fopen($file_name,'w+');
        fwrite($handle, $return);
        fclose($handle);
    }
    #Function to backup database to a zip file
function backup($username,$password,$db)
{
  $suffix = time();
  #Execute the command to create backup sql file
  exec("mysqldump --user={$username} --password={$password} --quick --add-drop-table --add-locks --extended-insert --lock-tables --all {$db} > backups/backup.sql");

  #Now zip that file
//  $zip = new ZipArchive();
//  $filename = "backups/backup-$suffix.zip";
//  if ($zip->open($filename, ZIPARCHIVE::CREATE) !== TRUE) {
//   exit("cannot open <$filename>\n");
//  }
//  $zip->addFile("backups/backup.sql" , "backup.sql");
//  $zip->close();
//  #Now delete the .sql file without any warning
//  @unlink("backups/backup.sql");
//  #Return the path to the zip backup file
  return "backups/backup-$suffix.sql";
} 

    function admin_download_ee() {
        // echo'sahbaj';
        $this->backup('ee_root', 'delisted_company', 'delisted_ee');
        //$this->admin_backup_tables('localhost', 'ee_root', 'delisted_company', 'delisted_ee');
//        $dbhost   = "localhost";
//        $dbuser   = "delisted_root";
//        $dbpwd    = "delisted_company";
//        $dbname   = "delisted_company";
//        $dumpfile = '/files/'.$dbname . "_" . date("Y-m-d_H-i-s") . ".sql";
//
//        passthru("/usr/bin/mysqldump --opt --host=$dbhost --user=$dbuser --password=$dbpwd $dbname > $dumpfile");
//
//        // report - disable with // if not needed
//        // must look like "-- Dump completed on ..." 
//
//        echo "$dumpfile "; passthru("tail -1 $dumpfile");
        $this->autoRender = false;
    }

    function admin_export($keyword=null) {
        $this->WorthlessShare->recursive = -1;
        // Find fields needed without recursing through associated models
        $worthlessshares = $this->WorthlessShare->find('all');

        $this->layout = false;
        $this->autoLayout = false;
        //   pr($worthlessshares);
        $this->set('worthlessshares', $worthlessshares);
    }

    function admin_upload_csv_ws() {
        if (!empty($this->data)) {
            //pr($this->data);
            $this->loadModel("WsShare");
            if (!empty($this->data['WsShare']['fileName']['name']) && is_uploaded_file($this->data['WsShare']['fileName']['tmp_name'])) {
                if ($this->data['WsShare']['fileName']['type'] == "text/comma-separated-values" OR $this->data['WsShare']['fileName']['type'] == "text/x-csv" OR $this->data['WsShare']['fileName']['type'] == "application/octet-stream" OR $this->data['WsShare']['fileName']['type'] == "application/vnd.ms-excel") {
                    //$fileData = fread(fopen(, "r"),$this->data['Codetail']['fileName']['size']);
                    $messages = $this->WsShare->import($this->data['WsShare']['fileName']['tmp_name']);
                    //debug($messages);
                    if (isset($messages['errors']) && count($messages['errors']) > 0) {
                        $msg = implode("<br>", $messages['errors']);
                    } else {
                        $msg = implode("<br>", $messages['messages']);
                    }
                    //echo $msg;
                    $this->Session->setFlash($msg);
                } else {
                    $this->Session->setFlash(__('Invalid file type. You must upload a CSV file.', true));
                }
            } else {
                $this->Session->setFlash(__('CSV File Required.', true));
            }
        }
    }

    function admin_upload_csv() {
        if (!empty($this->data)) {
            //pr($this->data);
            if (!empty($this->data['WorthlessShare']['fileName']['name']) && is_uploaded_file($this->data['WorthlessShare']['fileName']['tmp_name'])) {

                if ($this->data['WorthlessShare']['fileName']['type'] == "text/comma-separated-values" OR $this->data['WorthlessShare']['fileName']['type'] == "text/x-csv" OR $this->data['WorthlessShare']['fileName']['type'] == "application/octet-stream" OR $this->data['WorthlessShare']['fileName']['type'] == "application/vnd.ms-excel") {
                    //$fileData = fread(fopen(, "r"),$this->data['Codetail']['fileName']['size']);
                    $messages = $this->WorthlessShare->import($this->data['WorthlessShare']['fileName']['tmp_name']);
                    //debug($messages);
                    if (isset($messages['errors']) && count($messages['errors']) > 0) {
                        $msg = implode("<br>", $messages['errors']);
                    } else {
                        $msg = implode("<br>", $messages['messages']);
                    }
                    //echo $msg;
                    $this->Session->setFlash($msg);
                } else {
                    $this->Session->setFlash(__('Invalid file type. You must upload a CSV file.', true));
                }
            } else {
                $this->Session->setFlash(__('CSV File Required.', true));
            }
        }
    }

    function index() {
        $this->WorthlessShare->recursive = 0;
        $this->set('worthlessShares', $this->paginate());
    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid worthless share', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('worthlessShare', $this->WorthlessShare->read(null, $id));
    }

    function add() {
        if (!empty($this->data)) {
            $this->WorthlessShare->create();
            if ($this->WorthlessShare->save($this->data)) {
                $this->Session->setFlash(__('The worthless share has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The worthless share could not be saved. Please, try again.', true));
            }
        }
    }

    function edit($id = null) {

        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid worthless share', true));
            $this->redirect(array('action' => 'index'));
        }

        if (!empty($this->data)) {
            if ($this->WorthlessShare->save($this->data)) {
                $this->Session->setFlash(__('The worthless share has been saved', true));
                // $this->redirect(array('action' => 'index'));
                //$this->redirect($_SERVER['HTTP_REFERER']);
            } else {
                $this->Session->setFlash(__('The worthless share could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->WorthlessShare->read(null, $id);
        }
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for worthless share', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->WorthlessShare->delete($id)) {
            $this->Session->setFlash(__('Worthless share deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Worthless share was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

    function admin_index() {
        $this->layout = "viewlayout";
        $this->WorthlessShare->recursive = 0;
        $this->set('worthlessShares', $this->paginate());
    }

    function admin_search_ws_company_name() {
        $this->layout = "viewlayout";
        $this->WorthlessShare->recursive = 0;
        //$conditions=array('WorthlessShare.CompanyName like %'=>$this->data['WorthlessShare']['company_name'].'%');

        $this->paginate = array(
            'conditions' => array("WorthlessShare.CompanyName LIKE " => "%" . $this->data['WorthlessShare']['company_name'] . "%", "WorthlessShare.OrderNo !=" => "")
        );
        $this->set('worthlessShares', $this->paginate('WorthlessShare'));
    }
    function admin_search_ws_surname() {
        $this->layout = "viewlayout";
        $this->WorthlessShare->recursive = 0;
        //$conditions=array('WorthlessShare.CompanyName like %'=>$this->data['WorthlessShare']['company_name'].'%');

        $this->paginate = array(
            'conditions' => array("WorthlessShare.RegdName1 LIKE " => "%" . $this->data['WorthlessShare']['RegdName1'] . "%", "WorthlessShare.OrderNo !=" => "")
        );
        $this->set('worthlessShares', $this->paginate('WorthlessShare'));
    }

    function admin_view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid worthless share', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('worthlessShare', $this->WorthlessShare->read(null, $id));
    }

    function admin_add() {
        if (!empty($this->data)) {
            $this->WorthlessShare->create();
            if ($this->WorthlessShare->save($this->data)) {
                $this->Session->setFlash(__('The worthless share has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The worthless share could not be saved. Please, try again.', true));
            }
        }
    }

    function admin_edit($id = null) {

        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid worthless share', true));
            $this->redirect(array('action' => 'index'));
        }
        //print_r($this->data);
        if (!empty($this->data)) {
            $this->Security->validatePost = false;
            if ($this->WorthlessShare->save($this->data)) {
                $this->Session->setFlash(__('The worthless share has been saved', true));
                //$this->redirect(array('action' => 'index'));
                $this->redirect($_SERVER['HTTP_REFERER']);
            } else {
                $this->Session->setFlash(__('The worthless share could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->WorthlessShare->read(null, $id);
        }
    }

    function admin_search_line_no() {
        if (empty($this->data)) {
            $this->Session->setFlash(__('Invalid worthless share', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->redirect(array('action' => 'admin_edit', $this->data['WorthlessShare']['line_no']));
    }

    function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for worthless share', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->WorthlessShare->delete($id)) {
            $this->Session->setFlash(__('Worthless share deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Worthless share was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

}

?>